<!-- 流量计 -->
<template>
  <div class="flex-center table-top">
    <px-form ref="formRef" :model="queryParams" :inline="true" class="custom-form-ui search-form">
      <px-form-item label="设备编号" prop="eqpNo">
        <px-input v-model.trim="queryParams.eqpNo" style="width: 260px" placeholder="请输入设备编号" clearable />
      </px-form-item>
      <px-form-item label="气体种类" prop="type">
        <px-select
          v-model="queryParams.type"
          style="width: 260px"
          placeholder="请选择气体种类"
          multiple
          collapse-tags
          collapse-tags-tooltip
          clearable
          filterable
        >
          <px-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value" />
        </px-select>
      </px-form-item>
      <!-- <px-form-item label="日期" prop="date">
        <px-date-picker v-model="queryParams.date" type="date" placeholder="请选择日期" value-format="YYYY-MM-DD" style="width: 260px" />
      </px-form-item> -->
      <div class="search-form-btn">
        <px-button type="primary" @click="handleQuery">查询</px-button>
        <px-button @click="resetQuery">重置</px-button>
        <!-- <px-button v-has="`GAS_CONSUMPTION_BULKGAS_INSPECTION_BTN`" type="primary" :disabled="spotCheckDisabled" @click="spotCheckClick"
          >点检</px-button
        >
        <px-button v-has="`GAS_CONSUMPTION_BULKGAS_HISTORY_BTN`" type="primary" @click="spotCheckClickHistory">点检历史</px-button> -->
        <px-button v-has="`GAS_CONSUMPTION_BULKGAS_EXPORT_BTN`" @click="handleExport">导出</px-button>
      </div>
    </px-form>
  </div>
  <div ref="tableBoxRef" v-loading="tableLoading" class="table-content">
    <px-table :data="tableData" size="small" border class="common-table" :cell-style="tableCellStyle" :height="scrollbarHeight">
      <px-table-column type="index" label="序号" fixed width="55" align="center" />
      <px-table-column prop="gasName" label="气体种类" min-width="120" show-overflow-tooltip />
      <px-table-column prop="deviceCode" label="设备编号" min-width="120" show-overflow-tooltip />
      <!-- <px-table-column prop="itemName" label="项目" min-width="120" show-overflow-tooltip /> -->
      <px-table-column prop="statValue" label="实时流量(NM^3/H)" min-width="120" show-overflow-tooltip>
        <template #default="scope">
          <div v-if="scope.row.statValue !== null && scope.row.oos && scope.row.reason !== null && scope.row.reason !== ''">
            <px-popover
              placement="top-start"
              title="提示"
              :width="200"
              trigger="hover"
              :content="`${scope.row.itemKey} 机台用量超标。原因：${scope.row.reason}`"
            >
              <template #reference>
                <div class="date-cell">
                  <span :style="getCellStyle(scope.row)">
                    {{ scope.row.statValue }}
                  </span>
                </div>
              </template>
            </px-popover>
          </div>
          <div
            v-if="scope.row.statValue !== null && scope.row.oos && scope.row.reason === null && scope.row.reason === ''"
            class="date-cell"
            @click="setReason(scope.row, index)"
          >
            <span :style="getCellStyle(scope.row)">
              {{ scope.row.statValue }}
              <px-tooltip content="请发邮件咨询耗量异常原因，并回填结果">
                <px-icon>
                  <WarnTriangleFilled />
                </px-icon>
              </px-tooltip>
            </span>
          </div>
          <div v-if="!scope.row.oos" class="date-cell">
            <span>
              {{ scope.row.statValue }}
            </span>
          </div>
        </template>
      </px-table-column>
      <px-table-column prop="lslValue" label="SPEC L" min-width="120" show-overflow-tooltip />
      <!-- <px-table-column prop="showTargetValue" label="Target" min-width="120" show-overflow-tooltip /> -->
      <px-table-column prop="uslValue" label="SPEC U" min-width="120" show-overflow-tooltip />
      <!-- <px-table-column prop="dataTime" label="抄表日期" min-width="120" show-overflow-tooltip /> -->
      <px-table-column label="操作" width="150" fixed="right" align="center">
        <template #default="scope">
          <px-tooltip content="编辑" placement="top">
            <!-- :disabled="scope.row.itemName !== '日流量'" -->
            <px-button v-has="`GAS_CONSUMPTION_BULKGAS_EDIT_BTN`" link icon="EditPen" type="primary" @click="handleEdit(scope.row)" />
          </px-tooltip>
          <px-tooltip content="累计流量" placement="top">
            <px-button v-has="`GAS_CONSUMPTION_BULKGAS_FLOW_BTN`" link icon="chart" type="primary" @click="handleTotalFlow(scope.row)" />
          </px-tooltip>
          <px-tooltip content="曲线查看" placement="top">
            <px-button
              v-has="`GAS_CONSUMPTION_BULKGAS_CURVE_BTN`"
              link
              icon="BusinessMeasurement"
              type="primary"
              @click="handleViewLine(scope.row)"
            />
          </px-tooltip>
        </template>
      </px-table-column>
    </px-table>
  </div>

  <px-dialog v-model="editDialogVisible" title="编辑" width="400">
    <div class="dialog-wrap">
      <px-form ref="editFormRef" :model="editFormParams" class="left-form">
        <div class="title">固定值</div>
        <px-form-item label="SPEC L" prop="lslValue" label-width="80">
          <px-input v-model.trim="editFormParams.lslValue" placeholder="请输入" clearable />
        </px-form-item>
        <!-- <px-form-item label="Target" prop="targetValue" label-width="80">
          <px-input v-model="editFormParams.targetValue" placeholder="请输入" clearable />
        </px-form-item> -->
        <px-form-item label="SPEC U" prop="uslValue" label-width="80">
          <px-input v-model.trim="editFormParams.uslValue" placeholder="请输入" clearable />
        </px-form-item>
      </px-form>
      <!-- <div class="mid-wrap" />
      <px-form ref="editFormRef2" :model="editFormParams" class="right-form">
        <div class="title">计算公式</div>
        <px-form-item label="SPEC L = " prop="percentageLslValue" label-width="80">
          <div class="text">Target*</div>
          <px-input v-model="editFormParams.percentageLslValue" placeholder="请输入" clearable style="width: 80px" />
          <div class="text">%</div>
        </px-form-item>
        <px-form-item label="Target = " prop="percentageTargetValue" label-width="80">
          <px-input v-model="editFormParams.percentageTargetValue" placeholder="请输入" clearable style="width: 80px" />
          <div class="text">日均值</div>
        </px-form-item>
        <px-form-item label="SPEC U = " prop="percentageUslValue" label-width="80">
          <div class="text">Target*</div>
          <px-input v-model="editFormParams.percentageUslValue" placeholder="请输入" clearable style="width: 80px" />
          <div class="text">%</div>
        </px-form-item>
      </px-form> -->
    </div>
    <!-- <div class="text">注：优先按照固定值运行，无需固定值请空置</div> -->
    <template #footer>
      <span class="dialog-footer">
        <px-button @click="cancelEdit">取消</px-button>
        <px-button type="primary" @click="saveEdit">确定</px-button>
      </span>
    </template>
  </px-dialog>

  <px-dialog v-model="reasonDialogVisible" title="编辑" width="400">
    <px-form :model="reasonFormParams">
      <px-form-item label="原因" prop="reason">
        <px-input v-model.trim="reasonFormParams.reason" placeholder="请输入" clearable type="textarea" />
      </px-form-item>
    </px-form>
    <template #footer>
      <span class="dialog-footer">
        <px-button @click="cancelSetReason">取消</px-button>
        <px-button type="primary" @click="submitReason">确定</px-button>
      </span>
    </template>
  </px-dialog>

  <!-- 点检弹框  -->
  <div v-if="spotCheckDialogVisible">
    <SpotCheckDialog v-model:visible="spotCheckDialogVisible" :tableData="spotCheckHistorykData" />
  </div>

  <!-- 累计流量 -->
  <div v-if="totalFlowVisible">
    <TotalFlow v-model:visible="totalFlowVisible" :data="rowData" />
  </div>

  <!-- 曲线查看 -->
  <div v-if="viewCurveVisible">
    <!-- <ViewCurve v-model:visible="viewCurveVisible" fromPage="flowMeter" :data="rowData" /> -->
    <!-- 之前的压力表，有按照天、 时、分区分的，所以传参为pressure-->
    <ViewCurve v-model:visible="viewCurveVisible" fromPage="pressure" :data="rowData" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, onMounted, onUnmounted, getCurrentInstance } from "vue";
import { queryEquipSystem } from "@/api/equip/archive";
import { getFlowMeterListAPI, editPressureListAPI, setOOSReasonAPI } from "@/api/consumption/bulkGas";
import { PxMessage } from "px-ui";
import ViewCurve from "./viewCurve.vue";
import TotalFlow from "./totalFlow.vue";
import SpotCheckDialog from "../../component/spotCheckDialog.vue";
import { useSpotCheckHook, useExportHook } from "../../hook.js";
import { useUpdateDomHeight, useCancelUpdateDomHeight } from "@/hooks/useCommon";

const formRef = ref();
const editFormRef = ref();
const { proxy } = getCurrentInstance();

const gap = 40;
const defaultHeight = 606;
const scrollbarHeight = ref<number>(defaultHeight);
const tableBoxRef = ref<HTMLElement | null>(null);

const state = reactive({
  queryParams: {
    eqpNo: "",
    type: "",
    date: ""
  },
  editFormParams: {
    lslValue: "",
    targetValue: "",
    uslValue: "",
    percentageLslValue: "",
    percentageTargetValue: "",
    percentageUslValue: ""
  },
  reasonFormParams: {
    reason: ""
  },
  typeList: [],
  tableLoading: false,
  tableData: [],
  editDialogVisible: false,
  reasonDialogVisible: false,
  rowData: {},
  dateIndex: 0,
  viewCurveVisible: false,
  totalFlowVisible: false
});
const {
  queryParams,
  editFormParams,
  reasonFormParams,
  typeList,
  tableLoading,
  tableData,
  editDialogVisible,
  reasonDialogVisible,
  rowData,
  viewCurveVisible,
  totalFlowVisible
} = toRefs(state);

onMounted(async () => {
  getGasTypeList();
  handleQuery();
  await useUpdateDomHeight(scrollbarHeight, tableBoxRef, gap, defaultHeight);
});

onUnmounted(() => useCancelUpdateDomHeight());

const { spotCheckHistorykData, spotCheckDialogVisible, spotCheckDisabled, spotCheckClick, spotCheckClickHistory } = useSpotCheckHook("BULK_GAS");
const params = {
  itemKey: state.queryParams.eqpNo,
  gasSystemCode: state.queryParams.type.toString(),
  searchDate: state.queryParams.date
};
const { handleExport } = useExportHook(proxy, "BULK_GAS", params);

// 获取气体种类下拉框
const getGasTypeList = async () => {
  const res = await queryEquipSystem({ className: "GAS" });
  let facCode = localStorage.getItem("facCode");
  let t = null;
  // 一期
  if (facCode === "FAC_83abf9") {
    t = res.find(item => item.code === "SC2AC83D");
  } else {
    t = res.find(item => item.code === "SCF1924A");
  }
  if (!t?.children?.length) return;
  state.typeList = t.children.map(item => {
    let { name, code } = item;
    const reg = new RegExp("系统", "g");
    name = name.replace(reg, "");
    return { label: name, value: code };
  });
  state.typeList = state.typeList.filter(item => item.label !== "电气");
};

// 查询
const handleQuery = async () => {
  try {
    state.tableLoading = true;
    const { eqpNo, type, date } = state.queryParams;
    const params = {
      itemKey: eqpNo,
      gasSystemCode: type.toString(),
      searchDate: date
    };
    state.tableData = await getFlowMeterListAPI(params);
  } catch (err) {
    console.log(err);
  } finally {
    state.tableLoading = false;
  }
};

// 重置
const resetQuery = () => {
  formRef.value.resetFields();
  handleQuery();
};

const getCellStyle = item => {
  let style = {};
  if (item.oos) {
    style.color = "#fff";
  }
  return style;
};

// oos的数据单元格背景色为红色
const tableCellStyle = ({ row, column, rowIndex, columnIndex }) => {
  let style = {};
  if (row.statValue !== null && row.oos) {
    style.background = "#EF4444";
    style.color = "#fff";
  }
  return style;
};

// 编辑
const handleEdit = row => {
  state.editDialogVisible = true;
  state.rowData = row;
  state.editFormParams = {
    lslValue: row.lslValue,
    uslValue: row.uslValue
    // targetValue: row.targetValue,
    // percentageLslValue: row.percentageLslValue,
    // percentageTargetValue: row.percentageTargetValue,
    // percentageUslValue: row.percentageUslValue
  };
};

// 取消编辑
const cancelEdit = () => {
  editFormRef.value.resetFields();
  state.editDialogVisible = false;
};

// 保存编辑
const saveEdit = async () => {
  // const { lslValue, uslValue, targetValue, percentageLslValue, percentageTargetValue, percentageUslValue } = state.editFormParams;
  const { lslValue, uslValue } = state.editFormParams;
  if (parseFloat(lslValue) > parseFloat(uslValue)) {
    PxMessage.error("SPEC L 要小于等于 SPEC U");
    return;
  }
  const params = {
    itemKey: state.rowData.itemKey,
    lslValue: lslValue,
    uslValue: uslValue
    // targetValue: targetValue,
    // percentageLslValue: percentageLslValue,
    // percentageTargetValue: percentageTargetValue,
    // percentageUslValue: percentageUslValue
  };
  await editPressureListAPI(params);
  cancelEdit();
  handleQuery();
  PxMessage.success("修改成功");
};

const setReason = (row, index) => {
  state.rowData = row;
  state.dateIndex = index;
  state.reasonDialogVisible = true;
};

const cancelSetReason = () => {
  state.reasonDialogVisible = false;
};

const submitReason = async () => {
  if (!state.rowData.oos) return;
  const params = {
    itemKey: state.rowData.itemKey,
    statDate: state.rowData.dataTime,
    reason: state.reasonFormParams.reason
  };
  await setOOSReasonAPI(params);
  state.reasonDialogVisible = false;
  handleQuery();
  PxMessage.success("操作成功");
};

// 累计流量
const handleTotalFlow = row => {
  state.rowData = row;
  state.totalFlowVisible = true;
};

// 曲线查看
const handleViewLine = row => {
  state.rowData = row;
  state.viewCurveVisible = true;
};
</script>

<style lang="scss" scoped>
@import url("@/views/gas/consumption/scss/common.scss");
</style>
